package com.example.demo.service.impl;

import com.example.demo.bean.Elevator;
import com.example.demo.http.HttpAPIService;
import com.example.demo.repository.ElevatorRepository;
import com.example.demo.service.IElevatorService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by e on 2018/4/16 下午1:09
 *
 * @author <a href="https://eregg.com">eregg</a>
 */
@Service
public class ElevatorServiceImpl implements IElevatorService {
    
    @Autowired
    ElevatorRepository elevatorRepository;

    @Autowired
    HttpAPIService httpAPIService;

    @Override
    public void updateLocationAll() {

        String url = "http://api.map.baidu.com/place/v2/search";
        Map<String, Object> map = new HashMap<>();

        map.put("region", "锡林郭勒盟");
        map.put("output", "json");
        map.put("ak", "7BMD7AWXqI7Rk2FaLFZCGq9rfVi1HZu0");

        List<Elevator> elevators = this.elevatorRepository.findAll();
        for (Elevator elevator : elevators) {
            map.put("query", elevator.getAddress());

            try{
                String res = httpAPIService.doGet(url, map);
                JSONObject jsonObject = JSONObject.fromObject(JSONObject.fromObject(JSONArray.fromObject(JSONObject.fromObject(res).get("results")).get(0)).get("location"));
                elevator.setLat(jsonObject.get("lat").toString());
                elevator.setLng(jsonObject.get("lng").toString());
            }catch (Exception e){

            }

        }


        this.elevatorRepository.saveAll(elevators);

    }
}
